<template>
	<!-- 应收款-表格組件 -->
	<el-card>
		<el-form v-if="props.type === 'account'" :inline="true" :model="state.queryForm" label-width="140px" @keyup.enter="getDataList">
			<el-row>
				<el-col :span="8">
					<el-form-item label="TEl 电话">
						<el-input v-model="state.queryForm.customerMobile" placeholder="Please Input" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="Client 客户">
						<el-input v-model="state.queryForm.customerName" placeholder="please input a keyword" clearable></el-input>
						<!-- <el-select v-model="state.queryForm.customerName" remote remote-method="getCustomerList"
						filterable clearable placeholder="please input a keyword">
							<el-option
							v-for="item in customerOptions"
							:key="item.id"
							:label="item.name"
							:value="item.id"
							/>
						</el-select> -->
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="CNTNO 箱号">
						<el-input v-model="state.queryForm.cntNo" placeholder="Please Input" clearable></el-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="8">
					<el-form-item label="SystemNo 收据单号">
						<el-input v-model="state.queryForm.receiptNo" placeholder="Please Input" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="JobNumber 自编号">
						<el-input v-model="state.queryForm.jobNumber" placeholder="Please Input" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="SalesName 销售">
						<el-select v-model="state.queryForm.salesId" remote remote-method="getCustomerList"
						filterable clearable placeholder="please input a keyword">
							<el-option
							v-for="item in salesOptions"
							:key="item.id"
							:label="item.realName"
							:value="item.id"
							/>
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="8">
					<el-form-item label="CSName 客服">
						<el-select v-model="state.queryForm.csId" remote remote-method="getCustomerList"
						filterable clearable placeholder="please input a keyword">
							<el-option
							v-for="item in csOptions"
							:key="item.id"
							:label="item.realName"
							:value="item.id"
							/>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="Status 状态">
						<el-select v-model="state.queryForm.status" clearable>
							<el-option
							v-for="item in statusOptions"
							:key="item.value"
							:label="item.name"
							:value="item.value"
							/>
						</el-select>
					</el-form-item>
				</el-col>
				
			</el-row>
			<el-row>
				<el-col :span="16" :offset="11">
					<el-form-item>
						<el-button @click="getDataList">Query查询</el-button>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="addOrUpdateHandle()">Add新增</el-button>
					</el-form-item>
					<el-form-item>
						<el-button v-auth="'account:delete'" type="danger" @click="deleteBatchHandle()">Delete删除</el-button>
					</el-form-item>
					<el-form-item>
						<el-button type="info" @click="downloadInvoiceHandle()">Invoice Download下载发票</el-button>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<el-table
			v-loading="state.dataListLoading"
			:data="state.dataList"
			border
			style="width: 100%"
			@selection-change="selectionChangeHandle"
			@sort-change="sortChangeHandle"
		>
			<el-table-column type="selection" label="No. 序号" header-align="center" align="center" width="50"></el-table-column>
			<el-table-column prop="inventoryDate" label="Inventory date 入库日期" width="100" header-align="center" align="center" :formatter="inventoryDateFomat"> </el-table-column>
			<el-table-column prop="pickupDate" label="Pickup Date 提货日期" width="100" header-align="center" align="center" :formatter="pickupDateFomat"></el-table-column>
			<el-table-column prop="pickupDestination" label="Pickup destination 提货目的地" header-align="center" align="center"></el-table-column>
			<el-table-column prop="jobNumber" label="JOB NUMBER 自编号" header-align="center" align="center"></el-table-column>

			<el-table-column prop="cntNo" label="CTN NO 箱号" header-align="center" align="center"></el-table-column>
			<el-table-column prop="receiptNo" label="System NO 收据单号" header-align="center" align="center"></el-table-column>
			<el-table-column prop="customerName" label="CLEMENT 客户" header-align="center" align="center"></el-table-column>
			<el-table-column prop="customerMobile" label="TEL 电话" header-align="center" align="center" width="140"></el-table-column>
			<el-table-column prop="cnts" label="CTNS 箱数" header-align="center" align="center"></el-table-column>
			<el-table-column prop="grossWeight" label="GROSS WEIGHT 实重" header-align="center" align="center" width="120">
				<template #default="scope">
					<div>{{scope.row.grossWeight}}{{scope.row.grossWeightUnit}}</div>
				</template>
			</el-table-column>
			<el-table-column prop="chargeWeight" label="CHARGE WEIGHT 计费重" header-align="center" align="center" width="120">
				<template #default="scope">
					<div>{{scope.row.chargeWeight}}{{scope.row.grossWeightUnit}}</div>
				</template>
			</el-table-column>

			<el-table-column prop="unitPriceUsd" label="UNIT PRICE USD 美金单价" header-align="center" align="center"></el-table-column>
			<el-table-column prop="otherChargeUsd" label="OTHER CHARGE 美金其他费用" header-align="center" align="center"></el-table-column>

			<el-table-column prop="totalUsd" label="TOTAL USD 美金金额" header-align="center" align="center"></el-table-column>
			<el-table-column prop="unitPriceRmb" label="UNIT PRICE 人民币单价" header-align="center" align="center"></el-table-column>
			<el-table-column prop="otherChargeRmb" label="OTHER CHARGE 人民币其他费用" header-align="center" align="center"></el-table-column>
			<el-table-column prop="totalRmb" label="TOTAL RMB 人民币金额" header-align="center" align="center"></el-table-column>
			<el-table-column prop="note" label="NOTE 备注" header-align="center" align="center"></el-table-column>
			<el-table-column prop="salesName" label="Sales 销售" header-align="center" align="center"></el-table-column>
			<el-table-column prop="csName" label="CS 客服" header-align="center" align="center"></el-table-column>
			<el-table-column prop="status" label="Status 状态" header-align="center" align="center">
				<template #default="scope">
					<view v-if="scope.row.status">
						<span v-if="scope.row.status === 'Y'">Finished 已结清</span>
						<span v-if="scope.row.status === 'N'">NotFinished 未结清</span>
					</view>
				</template>
			</el-table-column>

			<el-table-column label="Operation 操作" fixed="right" header-align="center" align="center" width="240">
				<template #default="scope">
					<el-button v-if="type === 'account'" type="primary" link @click="toDetail(scope.row.id)">Detail详情</el-button>
					<el-button v-if="type === 'afterDown'" type="primary" link @click="toDetail(scope.row.id)">Receipt Detail Manage管理收款明细</el-button>
					<el-button v-auth="'account:update'" type="primary" link @click="addOrUpdateHandle(scope.row.id)">Update修改</el-button>
					<el-button v-auth="'account:delete'" type="primary" link @click="deleteBatchHandle(scope.row.id)">Delete删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:current-page="state.page"
			:page-sizes="state.pageSizes"
			:page-size="state.limit"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="sizeChangeHandle"
			@current-change="currentChangeHandle"
		>
		</el-pagination>
		<!-- 新增 / 修改 -->
		<add-or-update ref="addOrUpdateRef" :sales-options="salesOptions" :cs-options="csOptions" @refreshDataList="getDataList"></add-or-update>
	</el-card>
</template>

<script setup lang="ts">
import { useCrud } from '@/hooks'
import { reactive, ref } from 'vue'
import AddOrUpdate from './account-or-update.vue'
import DetailTable from '@/views/accountDetail/detail-table.vue'
import { IHooksOptions } from '@/hooks/interface'
import { downloadInvoice } from '@/api/receivable'
import { selectCustomerList } from '@/api/client'
import { queryUserInfo } from '@/api/user'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { useRouter } from 'vue-router'
import printJs from 'print-js'

const router = useRouter()

const props = defineProps({
	type: {
		type: String,

	},
	idList: {  //发票id集合
		type: Array,
		required: true
	}
})

let ids = [] as any[];
if(props.type === 'afterDown'){
	ids = props.idList;
}

const state: IHooksOptions = reactive({
	dataListUrl: '/receivables/page',
	deleteUrl: '/receivables/delete',
	queryForm: {
		customerMobile: '',
		customerName: '',
		cntNo: '',
		receiptNo: '',
		jobNumber: '',
		salesId: '',
		csId: '',
		idList: ids,
		status: ''
	}
})
const showIframe = ref(false)
const pdfIframe = reactive({
	pdfSrc: ''
})

// 客户选项下拉
const customerOptions = ref([]);
const getCustomerList = (query: string) => {
	let req = {
		page: 1,
		limit: 100,
		customerName: query
	}
	selectCustomerList(req).then(res => {
		customerOptions.value = res.data.list;
	})
}
getCustomerList('');

const statusOptions = [
	{ name: 'Finished 已结清', value: 'Y'},
	{ name: 'NotFinished 未结清', value: 'N'},
]

// 销售、客服选项下拉
const salesOptions = ref([]), csOptions = ref([]);
const getUsersList = (type: string) => {
	let req = {
		page: 1,
		limit: 100,
		roleName: type
	}
	queryUserInfo(req).then(res => {
		switch(type){
			case 'SALES': salesOptions.value = res.data.list; break;
			case 'CS': csOptions.value = res.data.list; break;
		}
	})
}
getUsersList('SALES');
getUsersList('CS');

const addOrUpdateRef = ref()
const addOrUpdateHandle = (id?: Number) => {
	addOrUpdateRef.value.init(id)
}

const inventoryDateFomat = (row, column) => {
	const inventoryDate = row.inventoryDate;
	let temp = '';
	if(inventoryDate && inventoryDate !== ''){
		temp = inventoryDate.split(' ')[0]
	}
	return temp
}
const pickupDateFomat = (row, column) => {
	const pickupDate = row.pickupDate;
	let temp = '';
	if(pickupDate && pickupDate !== ''){
		temp = pickupDate.split(' ')[0]
	}
	return temp
}
const downloadInvoiceHandle = async ()=>{
	let data = state.dataListSelections ? state.dataListSelections : [];
	if(data.length <= 0){
		ElMessage.error('Please select a receivable first 请先选择一项应收款');
		return ;
	}
	if(data.length > 10){
		ElMessage.error('Please select up to ten receivables first 请先选择十条以内的应收款');
		return ;
	}
	// 不能选择不同客服的应收款项下载
	for(let item of data){
		if(item.customerId !== data[0].customerId){
			ElMessage.error('Please select receivables from the same customers 请选择相同客户的应收款');
			return ;
		}
	}
	const loading = ElLoading.service({
		lock: true,
		text: 'Loading',
		background: 'rgba(0, 0, 0, 0.7)',
	})
	let temp = data.map(item => {
		return item.id
	})
	let resData = await downloadInvoice(temp).then((response: any) => {
		return response
	})
	if (resData) {
		const res = resData.data;
		const blob = new Blob([res]);//处理文档流
		
		// const fileName = resData.headers['content-disposition'].split('=')[1];
		const fileName = 'a.pdf'
		const down = document.createElement('a');
		down.download = fileName;
		down.style.display = 'none';
		down.href = URL.createObjectURL(blob);
		printJs({
			printable: down.href,
			type: 'pdf',
			fallbackPrintable: '',
			maxWidth: 800,
			scanStyles: false,
			onPrintDialogClose: () =>{
				loading.close();
				getDataList();
				ElMessageBox.confirm(
					'Whether to manage the collection details now 是否现在去管理收款明细？',
					'Warning',
					{
					confirmButtonText: 'OK',
					cancelButtonText: 'Cancel',
					type: 'warning',
					}
				).then(() => {
					router.push({path: '/receiveAccount/after-download', query: {idList: temp.join(',')}})
				}).catch(() => {
					
				})
			} 
		})
		return ;
		document.body.appendChild(down);
		down.click();
		URL.revokeObjectURL(down.href);  // 释放URL 对象
		document.body.removeChild(down); //下载完成移除
	} else {
		ElMessage.error('文件不存在');
	}
}

const toDetail = (id: any)=> {
	router.push({path: '/receiveAccount/account-detail', query: {id: id}})
}


const { getDataList, sizeChangeHandle, selectionChangeHandle, sortChangeHandle, currentChangeHandle, deleteBatchHandle } = useCrud(state)
</script>
